package org.wanda.pv.service.hy.impl;

import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import org.nutz.dao.Chain;
import org.nutz.dao.Cnd;
import org.nutz.dao.Condition;
import org.nutz.dao.Dao;
import org.nutz.http.Header;
import org.nutz.http.Response;
import org.nutz.json.Json;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.wanda.pv.framework.base.Result;
import org.wanda.pv.framework.utils.MyHttp;
import org.wanda.pv.model.file.FileUploadInfo;
import org.wanda.pv.model.hy.HyDrawing;
import org.wanda.pv.model.hy.HyProjectInfo;
import org.wanda.pv.model.hy.HySync2dDrawInfo;
import org.wanda.pv.model.hy.HyTree;
import org.wanda.pv.service.BaseServiceImpl;
import org.wanda.pv.service.file.FileUploadService;
import org.wanda.pv.service.hy.HyDrawingService;
import org.wanda.pv.util.HyUtil;
import org.wanda.pv.util.RotateImage;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author lxy
 * @date 2018/12/14 11:10
 */
@Service
public class HyDrawingServiceImpl extends BaseServiceImpl<HyDrawing> implements HyDrawingService {
    public HyDrawingServiceImpl(Dao dao) {
        super(dao);
    }

    private Logger logger= LoggerFactory.getLogger(this.getClass());
    @Autowired
    private FileUploadService fileUploadService;

    String hyUrl = "http://wd.minibim.com:8040/program/ws/v1/sync2dDraw";
    String localUrl = "http://localhost:8001/wandaPV/test/ws/v1/sync2dDraw";

    @Override
    public Result rotatePdfImage(Long drawingId , int angel){
        HyDrawing hyDrawing = dao().fetch(HyDrawing.class, drawingId);
        if (hyDrawing !=null) {
        FileUploadInfo fileUploadInfo = dao().fetch(FileUploadInfo.class, Cnd.where("id", "=", hyDrawing.getFid()).and("delFlag", "=", false));
        FileUploadInfo fileUploadInfo2 = dao().fetch(FileUploadInfo.class, Cnd.where("id", "=", hyDrawing.getTfid()).and("delFlag", "=", false));
        if (fileUploadInfo != null && fileUploadInfo2 != null ) {
            if (angel >= 0 || angel <= 360) {
                try {
                    RotateImage.RotateDrawingImage(fileUploadInfo.getServerPath(),angel);
                    RotateImage.RotateDrawingImage(fileUploadInfo2.getServerPath(),angel);
                } catch (Exception e) {
                    logger.error(e.getMessage(), e);
                    return Result.error("fail", "服务器内部错误!");
                }
            } else {
                return Result.error("旋转角度不合理！","旋转角度不合理！");
            }
        } else {
            return Result.error("该图纸文件还未转换图片！","该图纸文件还未转换图片！");
        }
    } else {
        return Result.error("图纸文件不存在！","图纸文件不存在！");
    }
        return  Result.success("success","图纸旋转成功！");
}

	@Override
    public void sync2dDraw(String projectFlowChildrenNodeId , String access_token){
		List<HyDrawing> hyDrawings = dao().query(HyDrawing.class, Cnd.where("latest", "=", true).and("project_flow_children_node_id","=",projectFlowChildrenNodeId).and("delFlag","=",false));
		List<HySync2dDrawInfo> hySync2DDrawInfos = new ArrayList<>();
		hyDrawings.forEach(hyDrawing -> {
			HySync2dDrawInfo hySync2DDrawInfo = new HySync2dDrawInfo();
			hySync2DDrawInfo.setFileName(hyDrawing.getFileName());
			hySync2DDrawInfo.setFilePath(hyDrawing.getFilePath());
			hySync2DDrawInfo.setProjectFlowChildrenNodeId(hyDrawing.getProjectFlowChildrenNodeId());
			hySync2DDrawInfo.setTreeId(hyDrawing.getFlowMapModelId());
			hySync2DDrawInfos.add(hySync2DDrawInfo);
		});
		HyUtil.sync2dDraw(access_token , hySync2DDrawInfos);
	}

    @Override
    public void initDrawings(String access_token_hy,String projectFlowChildrenNodeId,String projectId) {
      try {
          // 获取图纸文件的id 39
          HyTree parent = dao().fetch(HyTree.class, Cnd.where("parentId", "=", 0).and("name","=","图纸文件").and("type","=","drawing").and("delFlag","=","0"));
          //图纸文件节点下的所有的图纸父节点,比如 A-01 O方
          List<HyTree> hyTrees=dao().query(HyTree.class,Cnd.where("parentId","=",parent.getId()).and("delFlag","=","0"));
          hyTrees.forEach(hyTree -> {
              //这里就是和专业对应的节点一级 比如  01-AR建筑
              List<HyTree> hySpecs= dao().query(HyTree.class, Cnd.where("parentId", "=", hyTree.getId()).and("delFlag","=","0"));
              hySpecs.forEach(hyTree1->{
                  // 直接查询根节点下的图纸文件
                  List<HyDrawing> hyDrawings= HyUtil.getDrawings(access_token_hy,projectFlowChildrenNodeId,hyTree1.getId());
                  if (hyDrawings != null) {
                      hyDrawings.forEach(hyDrawing -> {
                          HyDrawing hyDrawing1 = null;
                          if (hyDrawing.getFileId() == null) {
                              hyDrawing1=dao().fetch(HyDrawing.class, (Condition) Cnd.where("file_name","=",hyDrawing.getFileName()).and("flow_map_model_id","=",hyDrawing.getFlowMapModelId()).and("project_flow_children_node_id","=",projectFlowChildrenNodeId));
                          } else {
                              hyDrawing1=dao().fetch(HyDrawing.class, (Condition) Cnd.where( "file_id","=",hyDrawing.getFileId()).and("flow_map_model_id","=",hyDrawing.getFlowMapModelId()).and("project_flow_children_node_id","=",projectFlowChildrenNodeId));
                          }
                          if(hyDrawing1 == null){
                              hyDrawing.setProjectFlowChildrenNodeId(projectFlowChildrenNodeId);
                              hyDrawing.setProjectId(projectId);
                              hyDrawing.setStatus(0);
                              hyDrawing= dao().insert(hyDrawing);
                              dao().update(HyDrawing.class, Chain.make("org_id",hyDrawing.getId()),Cnd.where("id","=",hyDrawing.getId()));
                          }
                      });
                  }
                  // 查询根节点下的子节点的图纸
                  List<HyTree> hyChildrenTrees=dao().query(HyTree.class,Cnd.where("parentId","=",hyTree1.getId()).and("delFlag","=","0"));
                 if (hyChildrenTrees != null ) {
                     hyChildrenTrees.forEach(hyTree2 ->{
                         List<HyDrawing> hyDrawings2 = HyUtil.getDrawings(access_token_hy,projectFlowChildrenNodeId,hyTree2.getId());
                        if (hyDrawings2 != null ) {
                            hyDrawings2.forEach(hyDrawing -> {
                                HyDrawing hyDrawing1 = null;
                                if (hyDrawing.getFileId() == null) {
                                    hyDrawing1=dao().fetch(HyDrawing.class, (Condition) Cnd.where("file_name","=",hyDrawing.getFileName()).and("flow_map_model_id","=",hyDrawing.getFlowMapModelId()).and("project_flow_children_node_id","=",projectFlowChildrenNodeId));
                                } else {
                                    hyDrawing1=dao().fetch(HyDrawing.class, (Condition) Cnd.where( "file_id","=",hyDrawing.getFileId()).and("flow_map_model_id","=",hyDrawing.getFlowMapModelId()).and("project_flow_children_node_id","=",projectFlowChildrenNodeId));
                                }
                                if(hyDrawing1 == null){
                                    hyDrawing.setProjectFlowChildrenNodeId(projectFlowChildrenNodeId);
                                    hyDrawing.setProjectId(projectId);
                                    hyDrawing.setStatus(0);
                                    hyDrawing= dao().insert(hyDrawing);
                                    dao().update(HyDrawing.class, Chain.make("org_id",hyDrawing.getId()),Cnd.where("id","=",hyDrawing.getId()));
                                }
                            });
                        }
                     });
                 }

              });

          });
          //查询出没有转jpg的数据
          List<HyDrawing> hyDrawings=dao().query(HyDrawing.class, Cnd.where("status","=",0));
          //修改项目状态
          HyProjectInfo hyProjectInfo=dao().fetch(HyProjectInfo.class,Cnd.where("id","=",projectId));
        /*  hyProjectInfo.setStatus(1);
          dao().update(hyProjectInfo);*/

          //先更改图纸的状态为初始化中
          hyDrawings.forEach(hyDrawing -> {
              hyDrawing.setStatus(1);
              dao().update(hyDrawing);
          });
          //对每张图纸进行初始化
          hyDrawings.forEach(hyDrawing -> {
              addDrawings(hyDrawing);
          });

          hyProjectInfo.setStatus(2);
          dao().update(hyProjectInfo);
      }catch (Exception e){
          logger.error(e.getMessage(),e);
      }
    }

    public void addDrawings(HyDrawing hyDrawing){
        try {
            Map<String,Object> map=fileUploadService.pdf2jpg(hyDrawing.getFilePath());
            Map<String,Object> map2=fileUploadService.pdf2Thumbnail(hyDrawing.getFilePath());
            hyDrawing.setTfid((Long) map2.get("tfid"));
            hyDrawing.setFid((Long) map.get("fid"));
            hyDrawing.setPngHeight((Integer) map.get("height"));
            hyDrawing.setPngWidth((Integer) map.get("width"));
            hyDrawing.setFileName((String) map.get("fileName"));
            hyDrawing.setStatus(2);
            dao().update(hyDrawing);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
